package com.example.service.order;


import cn.hutool.core.lang.Dict;
import cn.hutool.db.sql.Order;
import com.example.entity.orders.OrderDetails;
import com.example.entity.orders.Orders;
import com.example.entity.orders.orderDTO.OrderDetailsDTO;
import com.example.entity.orders.orderDTO.OrderProductDTO;
import com.example.entity.shop.SellerProduct;
import com.example.mapper.OrderDetailsMapper;
import com.example.mapper.OrdersMapper;
import com.example.mapper.SellerProductMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Title: OrderService
 * @Author 潘春兰
 * @Package com.example.service.order
 * @Date 2025/2/8 22:30
 * @description:
 * @Version:
 */
@Service
public class OrderService {
    @Resource
    private OrdersMapper orderMapper;
    @Resource
    private OrderDetailsMapper orderDetailsMapper;

    @Resource
    private SellerProductMapper sellerProductMapper;

    /**
     * 创建订单
     *
     * @param orders
     * @param orderDetailsList
     */
    @Transactional
    public void createOrder(Orders orders, List<OrderDetails> orderDetailsList) {
        // 生成订单编号
        String orderNumber = "OD" + generateOrderNumber();
        orders.setOrderNumber(orderNumber);
        orderMapper.insert(orders);
        //Orders order = orderMapper.selectByOrderNumber(orderNumber);
        Integer orderId = orders.getOrderId();
        //插入订单详情表
        for (OrderDetails orderDetail : orderDetailsList) {
            orderDetail.setOrderId(orderId);
            orderDetailsMapper.insert(orderDetail);
            //更新商品库存
            Integer productId = orderDetail.getProductId();
            Integer quantity = orderDetail.getQuantity();
            SellerProduct sellerProduct = sellerProductMapper.selectById(productId);
            sellerProduct.setCurrentStock(sellerProduct.getCurrentStock() - quantity);
            sellerProductMapper.updateById(sellerProduct);
        }


    }

    /**
     * 生成订单编号
     *
     * @return
     */
    public String generateOrderNumber() {
        long currentTimeMillis = System.currentTimeMillis();
        String orderNumber = "OD" + currentTimeMillis;
        return orderNumber;
    }


    /**
     * 分页查询
     */

    public PageInfo<Orders> selectAllByPage(Orders orders, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Orders> ordersList = orderMapper.selectAll(orders);
        return PageInfo.of(ordersList);
    }

    /**
     * 根据订单id查询订单详情
     */
    public OrderDetailsDTO selectOrderDetailsByOrderId(Integer orderId) {
        // 查询订单信息
        Orders order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        //查询对应订单的订单详情
        List<OrderDetails> orderDetailsList = orderDetailsMapper.selectByOrderId(orderId);

        //提取所有订单id
        List<Integer> productIds = orderDetailsList.stream().map(OrderDetails::getProductId).toList();
        //查询订单详情对应的商品信息
        List<SellerProduct> sellerProductList = sellerProductMapper.selectByIds(productIds);

        //将商品信息转换为Map,方便快速查找
        Map<Integer, SellerProduct> productMap = sellerProductList.stream()
                .collect(Collectors.toMap(SellerProduct::getSellerProductId, sellerProduct -> sellerProduct));
        //组装数据
        OrderDetailsDTO orderDetailsDTO = new OrderDetailsDTO();
        orderDetailsDTO.setOrder(order);
        orderDetailsDTO.setOrderDetails(orderDetailsList);
        //组装订单商品信息
        List<OrderProductDTO> orderProducts = new ArrayList<>();
        for (OrderDetails orderDetail : orderDetailsList) {
            SellerProduct sellerProduct = productMap.get(orderDetail.getProductId());
            if (sellerProduct != null) {
                OrderProductDTO orderProductDTO = new OrderProductDTO();
                orderProductDTO.setProduct(sellerProduct);
                orderProductDTO.setQuantity(orderDetail.getQuantity());
                orderProducts.add(orderProductDTO);
            }

        }

        orderDetailsDTO.setOrderProducts(orderProducts);
        return orderDetailsDTO;
    }

    /**
     * 修改订单状态
     *
     * @param orders
     */
    @Transactional
    public void updateOrderStatus(Orders orders) {
        if (orders.getOrderStatus().equals("3")) {
            //如果订单状态是“3”即同意退货，则更新商品库存
            List<OrderDetails> orderDetails = orderDetailsMapper.selectByOrderId(orders.getOrderId());
            for (OrderDetails orderDetail : orderDetails) {
                Integer id = orderDetail.getProductId();
                Integer quantity = orderDetail.getQuantity();
                SellerProduct sellerProduct = sellerProductMapper.selectById(id);
                if (sellerProduct != null) {
                    sellerProduct.setCurrentStock(sellerProduct.getCurrentStock() + quantity);
                    sellerProductMapper.updateById(sellerProduct);
                }
            }

        }
        orderMapper.updateById(orders);

    }

    /**
     * 根据订单编号查询
     *
     * @param orderNumber
     * @return
     */
    public Orders selectOrderByOrderNumber(String orderNumber) {
        return orderMapper.selectByOrderNumber(orderNumber);
    }


    /**
     * 批量删除
     *
     * @param orders
     */
    public void deleteBatch(List<Orders> orders) {
        for (Orders order : orders) {
            orderMapper.updateById(order);
        }
    }

    /**
     * 获取折线图数据
     *
     * @param days
     * @return
     */
    public List<Dict> countBuyerPayout(Integer days) {
        // 获取当前时间
        Date currentTime = new Date();

        // 计算指定天数前的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentTime);
        calendar.add(Calendar.DAY_OF_MONTH, -days);
        Date startTime = calendar.getTime();

        // 查询指定日期范围内的订单
        List<Orders> orders = orderMapper.findOrdersByDateRange(startTime, currentTime);

        // 将订单数据转换为适合 ECharts 折线图的数据格式
        List<Dict> result = new ArrayList<>();
        for (Orders order : orders) {
            Dict dict = new Dict();
            dict.put("date", order.getOrderCreateDate());
            dict.put("amount", order.getTotalPrice());
            result.add(dict);
        }

        return result;
    }


    /**
     * 获取商品销售量数据，饼状图数据
     *
     * @return
     */
    public List<Dict> countCategorySales(Orders order) {
        String orderStatus = order.getOrderStatus();
        List<OrderDetails> orderDetailsList = null;
        if(orderStatus.equals("3")){
            orderDetailsList = orderDetailsMapper.selectReturnCountQuantity();
        }else{
            // 查询订单细节表中的所有数据及对应的销量总和
            orderDetailsList = orderDetailsMapper.selectSalesCountQuantity();
        }


        // 查询订单表中包含的商品
        List<Integer> productIds = orderDetailsList.stream()
                .map(OrderDetails::getProductId)
                .distinct() // 去重，只需要每个商品一次
                .collect(Collectors.toList());

        // 查询所有商品信息
        List<SellerProduct> products = sellerProductMapper.selectByIds(productIds);

        // 将产品信息映射为 Map，以便通过 productId 查找对应的商品
        Map<Integer, SellerProduct> productMap = products.stream()
                .collect(Collectors.toMap(SellerProduct::getSellerProductId, product -> product));

        // 根据订单细节表的商品 ID 和销量总和，构造 Dict 列表
        return orderDetailsList.stream()
                .collect(Collectors.groupingBy(OrderDetails::getProductId,
                        Collectors.summingInt(OrderDetails::getQuantity)))
                .entrySet()
                .stream()
                .map(entry -> {
                    Integer productId = entry.getKey();
                    Integer totalQuantity = entry.getValue();

                    // 获取商品信息
                    SellerProduct product = productMap.get(productId);
                    if (product != null) {
                        // 使用 Dict 来存储结果
                        Dict result = Dict.create()
                                .set("productName", product.getProductName())
                                .set("totalQuantity", totalQuantity)
                                .set("category", product.getCategory());
                        return result;
                    }
                    return null;
                })
                .filter(dict -> dict != null)  // 过滤掉为 null 的条目
                .collect(Collectors.toList());
    }
}
